from django.shortcuts import render
from django.views import View
from utils.response import CommonResponseMixin, ReturnCode, wrap_json_response
from utils.auth import c2s, already_authorized
import json
from django.http import JsonResponse
from .models import User

# Create your views here.


class UserView(View, CommonResponseMixin):
    def get(self, request):
        # 判断是否登录，若已经登录，通过session中的open_id去数据库查询用户信息，并返回用户的相关信息。
        if not already_authorized(request):
            response = self.wrap_json_response(code=ReturnCode.SUCCESS)
            return JsonResponse(data=response, safe=False)
        open_id = request.session.get("open_id")
        user = User.objects.get(open_id=open_id)
        data = {}
        print(user.focus_cities)
        data['focus'] = {}
        data['focus']['city'] = json.loads(user.focus_cities)
        response = self.wrap_json_response(data=data, code=ReturnCode.SUCCESS)
        return JsonResponse(data=response, safe=False)

    def post(self, request):
        # if not already_authorized(request):
        #     response = self.wrap_json_response(code=ReturnCode.SUCCESS)
        #     return JsonResponse(data=response, safe=False)
        # open_id = request.session.get("open_id")
        # user = User.objects.get(open_id=open_id)
        #
        # received_body = request.body.decode("utf-8")
        # received_body = eval(received_body)
        # cities = received_body.get("city")
        # user.focus_cities = cities
        # user.save()
        # response = self.wrap_json_response(message="modify user info success", code=ReturnCode.SUCCESS)
        # return JsonResponse(data=response, safe=False)
        if not already_authorized(request):
            response = self.wrap_json_response(code=ReturnCode.SUCCESS)
            return JsonResponse(data=response, safe=False)
        open_id = request.session.get('open_id')
        user = User.objects.get(open_id=open_id)

        received_body = request.body.decode('utf-8')
        received_body = eval(received_body)

        cities = received_body.get('city')
        stocks = received_body.get('stock')
        constellations = received_body.get('constellation')

        user.focus_cities = json.dumps(cities)
        user.focus_stocks = json.dumps(stocks)
        user.focus_constellations = json.dumps(constellations)
        user.save()

        response = self.wrap_json_response(code=ReturnCode.SUCCESS, message='modify user info success.')
        return JsonResponse(data=response, safe=False)



def __authorize_by_code(request):
    # 使用wx.login获取的code到微信的接口
    post_data = request.body.decode("utf-8")
    post_data = json.loads(post_data)
    code = post_data.get("code").strip()
    appId = post_data.get("appId").strip()
    nickname = post_data.get("nickname").strip()
    response = {}
    if not code or not appId:
        response['message'] = "authorize failed, need entire authorization data"
        response["code"] = ReturnCode.BROKEN_AUTHORIZED_DATA
        return JsonResponse(data=response, safe=False)

    data = c2s(appId, code)
    openId = data.get("openid")
    print(f"[authorization-views.py-__authorize_by_code] get openid: {openId}")
    # 进行授权登录
    if not openId:
        response = wrap_json_response(code=ReturnCode.FAILED, message="auth")
        return JsonResponse(data=response, safe=False)

    request.session["open_id"] = openId
    request.session["is_authorized"] = True
    if not User.objects.filter(open_id=openId):  # 新用户
        new_user = User(open_id=openId, nickname=nickname)
        new_user.save()

    response = wrap_json_response(code=ReturnCode.SUCCESS, message="auth success")
    return JsonResponse(data=response, safe=False)


def authorize(request):
    return __authorize_by_code(request)